package com.example.learningnote.utils;

import android.content.Context;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

public class Http {
    private static final String TAG = "HTTP";
    private static final String BASE_URL = "https://api-harmony-teach.itheima.net/hm/";
    private static final long CONNECT_TIMEOUT = 10_000; // 连接超时，毫秒
    private static final long READ_TIMEOUT = 10_000; // 读取超时，毫秒

    private static OkHttpClient client;
    private static final Gson gson = new Gson();

    // 初始化 OkHttp 客户端
    public static void init(Context context) {
        // 配置日志拦截器
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(message -> Log.d(TAG, message));
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        // 配置 OkHttp 客户端
        client = new OkHttpClient.Builder()
                .connectTimeout(CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
                .readTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS)
                .addInterceptor(new AuthInterceptor(context))
                .addInterceptor(loggingInterceptor)
                .build();
    }

    // 认证拦截器，处理 token 和错误
    private static class AuthInterceptor implements Interceptor {
        private final Context context;

        private AuthInterceptor(Context context) {
            this.context = context;
        }

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            Request.Builder requestBuilder = originalRequest.newBuilder();
            String token = Memory.getInstance(context).get("access_token" , (String) null);
            if(token != null){
                // 除登录接口 外才需要加token
                // requestBuilder.addHeader("Authorization", "Bearer " + token);
            }
            Request request = requestBuilder.build();
            Response response = chain.proceed(request);
            // 处理 401 错误
            if (response.code() == 401) {

            }
            return response;
        }
    }

    // 通用 GET 请求
    public static <T> T get(String path, Map<String, String> queryParams, Class<T> responseType ) throws IOException {
        String url = BASE_URL + path;
        if (queryParams != null && !queryParams.isEmpty()) {
            StringBuilder query = new StringBuilder("?");
            for (Map.Entry<String, String> entry : queryParams.entrySet()) {
                query.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            url += query.substring(0, query.length() - 1); // 移除最后一个 &
        }

        Log.d(TAG , "URL " + url);
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("请求失败，状态码: " + response.code());
            }

            String responseBody = response.body().string();
            Log.d(TAG, "响应数据: " + responseBody);

            if (responseType == Map.class || responseType == List.class) {
                return gson.fromJson(responseBody, responseType);
            }

            return gson.fromJson(responseBody, responseType);
        } catch (IOException e) {
            Log.e(TAG, "GET 请求失败: " + e.getMessage());
            throw e;
        }
    }

    // 通用 POST 请求
    public static <T> T post(String path, Object data, Class<T> responseType, Context context) throws IOException {
        String url = BASE_URL + path;
        String jsonBody = gson.toJson(data);
        Log.d(TAG , "URL " + url);
        Request request = new Request.Builder()
                .url(url)
                .post(okhttp3.RequestBody.create(jsonBody, okhttp3.MediaType.parse("application/json")))
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("请求失败，状态码: " + response.code());
            }

            String responseBody = response.body().string();
            Log.d(TAG, "响应数据: " + responseBody);

            if (responseType == Map.class || responseType == List.class) {
                return gson.fromJson(responseBody, responseType);
            }

            return gson.fromJson(responseBody, responseType);
        } catch (IOException e) {
            Log.e(TAG, "POST 请求失败: " + e.getMessage());
            throw e;
        }
    }
}
